package shaw.wifi;

import shaw.wifi.gui.SecureConnectGui;
import shaw.wifi.network.AsyncNetworkTask;
import shaw.wifi.network.ConnectionInformation;
import android.util.Log;

public class NetworkSettingsTaskRunner {
	//the app can accept user input
	public static final int AVAILABLE = 0;
	
	//the app is connecting and will not allow users to edit the username/password/disable open
	public static final int CONNECTING = 1;
	
	//the app is canceling a connection
	public static final int CANCELING = 2;
	
	//the application can now read and set the state
	private int state = AVAILABLE;
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	
	//a task to get, update and set the network settings by connecting to the web application
	public AsyncNetworkTask getCurrentTask() {
		return task;
	}
	
	//login information
	private ConnectionInformation connInfo = new ConnectionInformation();
	protected ConnectionInformation getConnInfo() {
		return connInfo;
	}
	
	//current running task
	private AsyncNetworkTask task;
	
	//runs the network settings task(s) if it is not already running based on some login information gathered
	//hopefully from the GUI
	public void runNetworkSettingsTask() {
		if(state != AVAILABLE) {
			return;
		}
		task = NetworkSettingsTaskManager.get().getNextTask();
		if(task == null) {
			state = AVAILABLE;
			SecureConnectGui.get().setAsAvailable();
			return;
		}
		state = CONNECTING;
		task.execute(connInfo);
		SecureConnectGui.get().setAsConnecting();
	}
	
	//executed when the task is done, either by canceling it or allowing it to complete
	public void taskComplete() {
		Log.e("STATE", "TASK COMPLETE!!");
		NetworkSettingsTaskManager.get().taskComplete();
		SecureConnectGui.get().setAsAvailable();
		state = AVAILABLE;
		
		if(Constants._FINISHED == true) {
			SecureConnectGui.get().disableButton();
		}
		
		runNetworkSettingsTask();
	}
	
	//cancels the task, if possible
	//it should not be possible to cancel the task once it begins updating the network settings of the
	//device.
	public void cancelTask() {
		if(task != null) {
			boolean cancelable = task.getInterruptable();
			if(cancelable) {
				SecureConnectGui.get().addLineToOutput("Canceling...");
				NetworkSettingsTaskManager.get().clearTasks();
				boolean interrupted = task.cancel(true);
				if(interrupted) {
					taskComplete();
				}
			}
		}
	}
}
